package sa.com.sure.ejtimaa.database;


import sa.com.sure.ejtimaa.common.AppHelper;
import sa.com.sure.ejtimaa.model.MeetingSessionInfo;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;


public class MeetingSessions {

	private DataBaseHelper dbHelper;
	
	public static final String TABLE_Name = "MeetingSessions";
	
    public static final String SessionIDField = "SessionID"; 
    public static final String SessionNameField = "SessionName";
    
    private String[] allColumns = { SessionIDField, SessionNameField  };
    
    Cursor cursor = null;
    
    public MeetingSessions(Context context)  {
 		dbHelper = new DataBaseHelper(context);
 		dbHelper.createDataBase();
 	}
        
    public static MeetingSessions Instance = new MeetingSessions(AppHelper.getAppContext());
    
	public void open() throws SQLException {
		dbHelper.openDataBase();
	}
	
	public void close() {
		if(cursor!=null && !cursor.isClosed())
			cursor.close();
		dbHelper.close();
	}
	
	public void addItem(MeetingSessionInfo item) { 
       
		try{
			
			open();
			
	        ContentValues values = new ContentValues(); 
	        
	        values.put(SessionIDField, item.GetSessionID()); 
	        values.put(SessionNameField, item.GetSessionName()); 
	        
	        dbHelper.db.insert(TABLE_Name, null, values); 
		}
		finally{
			
			close();
		}
        
    } 
	
	
	public MeetingSessionInfo GetItem(int SessionID) throws SQLException{

		try
		{
				open();
			
				MeetingSessionInfo item = null;
				
				cursor = dbHelper.db.query(TABLE_Name,allColumns, SessionIDField + "=" + SessionID ,null,null,null,null);
		        if (cursor != null ) {
		        	cursor.moveToFirst();	
		        	if(cursor.getCount()>0)
		        		item =   getItemInfo(cursor);
		        }	        
		        		        
		    	return item;
		}
		finally{
			
			close();
		}   	
    		    
	}
	
	 public boolean updateItem(MeetingSessionInfo item) {
		 
		 try{		 
		 	open();
		 	
		    ContentValues args = new ContentValues();		    
		    args.put(SessionNameField, item.GetSessionName());		    
		    boolean res =   dbHelper.db.update(TABLE_Name, args, SessionIDField + "=" + item.GetSessionID() , null) > 0;
		    		    
		    return res;
		}
		finally{
			
			close();
		}		    
	 }
	
	
    private MeetingSessionInfo getItemInfo(Cursor cursor) {  
  
    	return new MeetingSessionInfo(cursor.getInt(0),cursor.getString(1));    	   
	}
}
